package com.fengye.school.service;

import com.fengye.school.model.school.School;
import com.fengye.school.response.ResponsePageResult;
import com.fengye.school.respository.SchoolRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class SchoolService {

    @Resource
    private SchoolRepository schoolRepository;

    @Transactional
    public School save(School school){
        return this.schoolRepository.save(school);
    }

    public List<School> list() {
        List<School> all = schoolRepository.findAll();
        return all;
    }

    public Optional<School> getById(Long id){
        return schoolRepository.findById(id);
    }

    public ResponsePageResult<School> listByPage(int page, int size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<School> all = schoolRepository.findAll(pageable);
        long allTotalElements = all.getTotalElements();// 总条目
        int totalPages = all.getTotalPages(); // 总页数
        List<School> content = all.getContent(); // 该页的具体数据
        int number = all.getNumber();// 当前是第几页
        return ResponsePageResult.success("获取学院列表成功", all.getTotalElements(), all.getContent());
// return all;
//         return content;
//         return all;
    }

    public void deleteAll(Long[] ids) {
        Arrays.stream(ids).forEach(id -> schoolRepository.deleteById(id));
    }

    public void deleteById(Long id) {
        schoolRepository.deleteById(id);
    }
}
